package ebiz.buddhist.texts;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;
import ebiz.buddhist.texts.network.NetworkUtil;

import com.nbpcorp.mobilead.sdk.MobileAdListener;
import com.nbpcorp.mobilead.sdk.MobileAdView;

public class BuddhistTextsView extends Activity implements MobileAdListener {
	ArrayList<String> mList;
	ProgressDialog mProgress;
	SeekBar mSeekbar;
	MediaPlayer mPlayer;
	TelephonyManager mTelMan; //------- 통화시 mp3 play 중지 
	WebView webview;
	private MobileAdView adView = null;
	
	int mValue;
	Button mPlayBtn;
	boolean wasPlaying;
	boolean isMpCheck;
	boolean isDownCheck = false; 
	boolean isMediaCheck = false; // sekisuri searchActivity 에서 왔는지 체크
	boolean mResumeAfterCall; //------- 통화시 mp3 play 중지 

	String compareStr;
	String mpPathStr;
	String RenameStr;
	String strMenuname="";
	String strMedia;
	String urlPath;

	//public String[] intentEx = {"han_heartsutra.mp3","prajna.mp3","han_chunsu.mp3","sinmyo.mp3",
	//		"yebull.mp3","chunsu.mp3","heartsutra.mp3","sinju.mp3","beopseong.mp3","chunji.mp3"
	//		,"ami.mp3","diamond_sutra.mp3","semin_hwaeom.mp3","semin_valwon.mp3"};
	public String[] intentEx = {
			"chunsu.mp3","han_chunsu.mp3",
			"heartsutra.mp3","han_heartsutra.mp3",
			"sinju.mp3","beopseong.mp3",
			"chunji.mp3","diamond_sutra.mp3",
			"semin_hwaeom.mp3","semin_valwon.mp3",
			"ami.mp3","sinmyo.mp3",
			"yebull.mp3","prajna.mp3"
			};
	
	public String[] strUrl = {
			"file:///android_asset/chunsu.html","file:///android_asset/han_chunsu.html",
			"file:///android_asset/heartsutra.html","file:///android_asset/han_heartsutra.html",
			"file:///android_asset/sinju.html","file:///android_asset/beopseong.html",
			"file:///android_asset/chunji.html","file:///android_asset/diamondsutra.html",
			"file:///android_asset/hwaeom.html","file:///android_asset/valwon.html",
			"file:///android_asset/ami.html","file:///android_asset/sinmyo.html",
			"file:///android_asset/yebull.html","file:///android_asset/prajna.html",
			};
	int menuNum;
	ConnectivityManager cMgr;
	
	
   @Override
   public void onCreate(final Bundle savedInstanceState) {
	  
      super.onCreate(savedInstanceState);
      this.setContentView(R.layout.html_view);
      // adView 만들기
      adView = (MobileAdView) findViewById(R.id.adview1);
      adView.setListener(this);
	  adView.start();
	  
		
		
      mList = new ArrayList<String>();
	  mPlayer = new MediaPlayer();
	  compareStr = revIntent();
	// sekisuri searchActivity 에서 보내온 문자열이면 && 제거 <--	
	  String strSub = compareStr.substring(0,2);

	  if(strSub.compareTo("&&")== 0)
	  {
		  int len = compareStr.length();
		  compareStr = compareStr.substring(2,len);
		  strMedia = compareStr;
		  int end = strMedia.lastIndexOf('/');
		  compareStr = strMedia.substring(end+1);
		  Log.e("compareStr", compareStr);
		  if(compareStr.compareTo("han_heartsutra.mp3")== 0 ||
			 compareStr.compareTo("heartsutra.mp3")== 0	||
			 compareStr.compareTo("han_chunsu.mp3")== 0	||
			 compareStr.compareTo("chunsu.mp3")== 0 ||
			 compareStr.compareTo("beopseong.mp3")==0 ||
			 compareStr.compareTo("yebull.mp3")==0 ||
			 compareStr.compareTo("prajna.mp3")==0 ||
			 compareStr.compareTo("sinmyo.mp3")==0 ||
			 compareStr.compareTo("sinju.mp3")==0  ||
			 compareStr.compareTo("ami.mp3")==0	||
			 compareStr.compareTo("diamond_sutra.mp3")==0

			 )
		  {
		      urlPath = "file:///android_asset/" + compareStr.replaceAll("(?i)mp3", "html");
	       		Log.e("urlPath", urlPath);

		  }
		  Log.e("strMedia", strMedia);
		  isMediaCheck = true;
		  
	  }
	// -->
	  RenameStr = mpReName(compareStr);
	  if(compareStr.compareTo("han_heartsutra.mp3")== 0)
	  {
		  strMenuname = getString(R.string.item_kor_heartsutra);
	  }
	  if(compareStr.compareTo("heartsutra.mp3")== 0)
	  {
		  strMenuname = getString(R.string.item_sutra);
	  }
	  if(compareStr.compareTo("han_chunsu.mp3")== 0)
	  {
		  strMenuname = getString(R.string.item_kor_chunsu);
	  }
	  if(compareStr.compareTo("chunsu.mp3")== 0)
	  {
		  strMenuname = getString(R.string.item_chunsu);
	  }
	  if(compareStr.compareTo("beopseong.mp3")==0)
	  {
		  strMenuname = getString(R.string.item_beopseong);
	  }
	  if(compareStr.compareTo("yebull.mp3")==0)
	  {
		  strMenuname = getString(R.string.item_yebull);
	  }
	  if(compareStr.compareTo("prajna.mp3")==0)
	  {
		  strMenuname = getString(R.string.item_prajna);
	  }
	  if(compareStr.compareTo("sinmyo.mp3")==0)
	  {
		  strMenuname = getString(R.string.item_sinmyo);
	  }
	  if(compareStr.compareTo("ami.mp3")==0)
	  {
		  strMenuname = getString(R.string.item_ami);
	  }
	  if(compareStr.compareTo("diamond_sutra.mp3")==0)
	  {
		  strMenuname = getString(R.string.item_diamond);
	  }
	  if(compareStr.compareTo("semin_hwaeom.mp3")==0)
	  {
		  strMenuname = getString(R.string.item_hwaeom);
	  }
	  if(compareStr.compareTo("semin_valwon.mp3")==0)
	  {
		  strMenuname = getString(R.string.item_valwon);
	  }
	  
      webview = (WebView) findViewById(R.id.webkit);
      WebSettings ws = webview.getSettings();

      ws.setJavaScriptEnabled(true);		// 잡스크립트실행여부
      ws.setJavaScriptCanOpenWindowsAutomatically(true);      
   ws.setDomStorageEnabled(true);
      
      Uri u = getIntent().getData();
      if(urlPath != null)
      {
          webview.loadUrl(urlPath);
      }
      else
      {
          webview.loadUrl(u.toString());
      }
            
     //------- 통화시 mp3 play 중지 
      mTelMan = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
	  mTelMan.listen(mCallListener, PhoneStateListener.LISTEN_CALL_STATE);
	  //------- 통화시 mp3 play 중지 
	  mPlayBtn = (Button)findViewById(R.id.play);
	// 완료 리스너, 시크바 변경 리스너 등록
	  mPlayer.setOnCompletionListener(mOnComplete);
	  mPlayer.setOnSeekCompleteListener(mOnSeekComplete);		
	  mSeekbar = (SeekBar)findViewById(R.id.viewseekbar);
	  mSeekbar.setOnSeekBarChangeListener(mOnSeek);
	  mSeekbarHandler.sendEmptyMessageDelayed(0,200);

	  mpInit();			
   }
   public void mpInit()
   {
	   if(isMediaCheck)
	   {
		   mpPathStr = strMedia;
	   }
	   else
	   {
		   mpPathStr =  FileNameSearch(compareStr);
	   }
	// 첫 곡 읽기 및 준비
	//	Toast.makeText(BuddhistTextsView.this, compareStr, Toast.LENGTH_LONG).show();

		if (LoadMedia(mpPathStr) == false) {
			mPlayBtn.setText(RenameStr + getString(R.string.menu_down));
			mSeekbar.setVisibility(View.GONE); // mp파일이 없을시 seekbar를 지운다
			isMpCheck = false;			
		}    
		else
		{			
			isMpCheck = true;
		}
   }
   
   Handler mSeekbarHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (mPlayer == null) return;
			if (mPlayer.isPlaying()) {
				mSeekbar.setProgress(mPlayer.getCurrentPosition());
			}
			mSeekbarHandler.sendEmptyMessageDelayed(0,200);
		}
	};
// 재생 위치 이동
	SeekBar.OnSeekBarChangeListener mOnSeek = 
		new SeekBar.OnSeekBarChangeListener() {
		public void onProgressChanged(SeekBar seekBar, 
				int progress, boolean fromUser) {
			if (fromUser) {
				mPlayer.seekTo(progress);
			}
		}

		public void onStartTrackingTouch(SeekBar seekBar) {
			wasPlaying = mPlayer.isPlaying();
			if (wasPlaying) {
				mPlayer.pause();
			}
		}

		public void onStopTrackingTouch(SeekBar seekBar) {
		}
	};
	
	
   public String mpReName(String str)
   {
	   String strCompare = str;
	   if(strCompare.compareTo("chunsu.mp3")== 0)
		   strCompare = getString(R.string.mp3_chunsu);
	   if(strCompare.compareTo("han_chunsu.mp3")== 0)
		   strCompare = getString(R.string.mp3_kor_chunsu);
	   if(strCompare.compareTo("heartsutra.mp3")== 0)
		   strCompare = getString(R.string.mp3_sutra);
	   if(strCompare.compareTo("han_heartsutra.mp3")== 0)
		   strCompare = getString(R.string.mp3_kor_heartsutra);
	   if(strCompare.compareTo("sinju.mp3") == 0)
		   strCompare = getString(R.string.mp3_sinju);
	   if(strCompare.compareTo("chunji.mp3")==0)
		   strCompare = getString(R.string.mp3_chunji);
	   if(strCompare.compareTo("beopseong.mp3")==0)
		   strCompare = getString(R.string.mp3_beopseong);
	   if(strCompare.compareTo("yebull.mp3")==0)
		   strCompare = getString(R.string.mp3_yebull);
	   if(strCompare.compareTo("prajna.mp3")==0)
		   strCompare = getString(R.string.mp3_prajna);
	   if(strCompare.compareTo("sinmyo.mp3")==0)
		   strCompare = getString(R.string.mp3_sinmyo);
	   if(strCompare.compareTo("ami.mp3")==0)
		   strCompare = getString(R.string.mp3_ami);
	   if(strCompare.compareTo("diamond_sutra.mp3")==0)
		   strCompare = getString(R.string.mp3_diamond);
	   
	   if(strCompare.compareTo("semin_hwaeom.mp3")==0)
		   strCompare = getString(R.string.item_semin2);
	   if(strCompare.compareTo("semin_valwon.mp3")==0)
		   strCompare = getString(R.string.mp_valwon);
	   
	   return strCompare;
   }
   
   public String FileNameSearch(String strPath)
	{
	    String path;
		File SDCardRoot = Environment.getExternalStorageDirectory(); 
        File dir = new File(SDCardRoot + "/buddhist/");
		if(dir!=null) {
			File[] dirs = dir.listFiles();
			if(dirs!=null) {
				for(int i=0; i<dirs.length; i++) {					
					if(dirs[i].getName().endsWith("mp3")) {
						path = dirs[i].getName();
						if(path.compareTo(strPath) == 0) 
						{
							return dirs[i].getAbsolutePath();
						}
					}
				}
			}
		}
		
		return  strPath;
	}
  
   // 항상 준비 상태여야 한다.
   boolean LoadMedia(String idx) {
		try {
			mPlayer.setDataSource(idx);
		} catch (IllegalArgumentException e) {
			return false;
		} catch (IllegalStateException e) {
			return false;
		} catch (IOException e) {
			return false;
		}
		if (Prepare() == false) {
			return false;
		}
		mSeekbar.setMax(mPlayer.getDuration());
		return true;
   }
   
   boolean Prepare() {
		try {
			mPlayer.prepare();
		} catch (IllegalStateException e) {
			return false;
		} catch (IOException e) {
			return false;
		}
		return true;
   }
// 재생 완료되면 다음곡으로
   MediaPlayer.OnCompletionListener mOnComplete = 
   	new MediaPlayer.OnCompletionListener() {
		public void onCompletion(MediaPlayer arg0) {
			mPlayBtn.setText(getString(R.string.btn_play));
		}
   };
   // 위치 이동 완료 처리
   MediaPlayer.OnSeekCompleteListener mOnSeekComplete = 
   	new MediaPlayer.OnSeekCompleteListener() {
		public void onSeekComplete(MediaPlayer mp) {
			if (wasPlaying) {
				mPlayer.start();
			}
		}
   };
   public String revIntent()
   {
	   Intent intent = getIntent();
	   String text = intent.getStringExtra("TextIn");
	   return text;
   }
   public int SearchUrl()
   {
	   int i;
	   for(i=0;i < 12;i++)
	   {
		   if(compareStr.compareTo(intentEx[i])==0)
			   break;
	   }
	   return i;
   }
   public void mOnClick(View v) {
   	switch (v.getId()) {
       // 재생 및 일시 정지
   	case R.id.play:
   		if(isDownCheck == true)
   		{
   			finish();
   			int i = SearchUrl();
   			CommAct(strUrl[i],i);	
   		}
   		if(isMpCheck == false)
   		{
   			cMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
   			String ext = Environment.getExternalStorageState();

   		 	if (ext.equals(Environment.MEDIA_MOUNTED) == false) {
   		 		Toast.makeText(this, getString(R.string.message_sdcard), 1).show();
   		 		break;
   		 	}
 		
   			if (NetworkUtil.connectionPresent(cMgr)) { 		
   				if(isDownCheck == false)
   				{
   					alertDown();
   					mPlayBtn.setText(getString(R.string.btn_refresh));
   					isDownCheck = true;
   				}
   			} else {
   				Toast.makeText(BuddhistTextsView.this, getString(R.string.networkerror), Toast.LENGTH_LONG).show();
   			}
   		}
   		else
   		{
			if (mPlayer.isPlaying() == false) {
				mPlayer.start();
				mPlayBtn.setText(getString(R.string.btn_pause));
			} else {
				mPlayer.pause();
				mPlayBtn.setText(getString(R.string.btn_play));
			}
   		}
   		break;
   	  	}
   }
	void doDownload() {
		new AccumulateTask().execute(100);
	}
	void alertDown()
	{
		new AlertDialog.Builder(BuddhistTextsView.this)
		.setTitle(getString(R.string.dialog_alert))
		.setMessage(getString(R.string.dialog_message_down))
		.setPositiveButton(getString(R.string.dialog_yes), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {			
				doDownload();				
			}
		})				
		.setNegativeButton(getString(R.string.dialog_no), null)
		.show();
	}
	  //------- 통화시 mp3 play 중지 
	PhoneStateListener mCallListener = new PhoneStateListener() {
		public void onCallStateChanged (int state, String incomingNumber) {
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE:
				if (mResumeAfterCall) {
				/*	
					mTextCall.postDelayed(new Runnable() {
						public void run() {
							mPlayer.start();
						}
					}, 3000);
				*/	
					mPlayer.start();
				}
				break;
			case TelephonyManager.CALL_STATE_RINGING:
				// 전화오면 즉시 재생 중지
				if (mPlayer.isPlaying()) {
					mPlayer.pause();
					mResumeAfterCall = true;
				} else {
					mResumeAfterCall = false;
				}
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:
				break;
			}
		}
	};
	  //------- 통화시 mp3 play 중지 
	
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0,1,0,getString(R.string.item_chunsu));
		menu.add(0,2,0,getString(R.string.item_kor_chunsu));
		menu.add(0,3,0,getString(R.string.item_sutra));
		menu.add(0,4,0,getString(R.string.item_kor_heartsutra));
		menu.add(0,5,0,getString(R.string.item_sinju));
		SubMenu etc = menu.addSubMenu(getString(R.string.menu_more));
		etc.add(0,6,0,getString(R.string.item_beopseong));
		etc.add(0,7,0,getString(R.string.item_chunji));
		etc.add(0,8,0,getString(R.string.item_diamond));
		etc.add(0,9,0,getString(R.string.item_hwaeom));
		etc.add(0,10,0,getString(R.string.item_valwon));
		etc.add(0,11,0,getString(R.string.item_ami));
		etc.add(0,12,0,getString(R.string.item_yebull));
		etc.add(0,13,0,getString(R.string.item_prajna));
		return true;
	}
	public void CommAct(String exput,int position)
	{
		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(exput),
                this, BuddhistTextsView.class);
		intent.putExtra("TextIn",intentEx[position]);
		startActivity(intent);
	}
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
			finish();
			CommAct(strUrl[0],0);		
			return true;			
		case 2:
			finish();
			CommAct(strUrl[1],1);		
			return true;	
		case 3:
			finish();
			CommAct(strUrl[2],2);		
			return true;	
		case 4:
			finish();
			CommAct(strUrl[3],3);		
			return true;	
		case 5:
			finish();
			CommAct(strUrl[4],4);		
			return true;	
		case 6:
			finish();
			CommAct(strUrl[5],5);		
			return true;	
		case 7:
			finish();
			CommAct(strUrl[6],6);		
			return true;	
		case 8:
			finish();
			CommAct(strUrl[7],7);		
			return true;	
		case 9:
			finish();
			CommAct(strUrl[8],8);
			return true;
		case 10:
			finish();
			CommAct(strUrl[9],9);
			return true;
		case 11:
			finish();
			CommAct(strUrl[10],10);
			return true;
		case 12:
			finish();
			CommAct(strUrl[11],11);
			return true;
		case 13:
			finish();
			CommAct(strUrl[12],12);
			return true;
		}
		
		return false;
	}
   class AccumulateTask extends AsyncTask<Integer, Integer, Integer> {
		@SuppressWarnings("deprecation")
		protected void onPreExecute() {
			mValue = 0;
			mProgress = new ProgressDialog(BuddhistTextsView.this);
			mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setTitle(getString(R.string.dialog_alert));
			mProgress.setMessage(getString(R.string.dialog_down));
			mProgress.setCancelable(false);
			mProgress.setProgress(0);
			mProgress.setButton(getString(R.string.dialog_stop), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					cancel(true);
				}
			});
			mProgress.show();
		}
		
		protected Integer doInBackground(Integer... arg0) {
			while (isCancelled() == false) { 
			//	mValue++;
				if (mValue <= 100) {
					publishProgress(mValue);
				} else {
					//String str = mValue + " ";
					//Toast.makeText(maincon, str, Toast.LENGTH_SHORT).show();
					break;
				}
				try { 
					 	//String urlstr = "http://sekisuri.cafe24.com/buddhist/music/";
						String urlstr = "https://sites.google.com/site/sekisuri/";
						String strMpUrl = "https://sites.google.com/site/sowasowahot/";

						String mpfilestr;
						if(compareStr.compareTo("diamond_sutra.mp3")== 0)
						{
							mpfilestr = strMpUrl + compareStr;
						}
						else
						{
							mpfilestr = urlstr + compareStr;
						}

					    URL url = new URL(mpfilestr);
					   
				        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();   
				        urlConnection.setRequestMethod("GET");   
				        urlConnection.setDoOutput(true);   
				        urlConnection.connect();   
				        int totalSize = urlConnection.getContentLength();   
				        int downloadedSize = 0;  
				        if(totalSize <= 0)
				        {
				        	 mValue = 101;					        	
					         Thread.sleep(50); 
				        }
				        else
				        {
					        File SDCardRoot = Environment.getExternalStorageDirectory(); 
					        File path = new File(SDCardRoot + "/buddhist/");
					        if(! path.isDirectory()) {
					                path.mkdirs();
					          }
					        File file = new File(path, compareStr);   
					        FileOutputStream fileOutput = new FileOutputStream(file);   
					        InputStream inputStream = urlConnection.getInputStream();   
					       
			//		        int totalSize = urlConnection.getContentLength();   
			//		        int downloadedSize = 0;   
				                
					        byte[] buffer = new byte[1024];   
					        int bufferLength = 0;
					         while ( (bufferLength = inputStream.read(buffer)) > 0 ) {   
					         fileOutput.write(buffer, 0, bufferLength);   
					         downloadedSize += bufferLength;   
					             updateProgress(downloadedSize, totalSize); 
					         }
					         mValue = 101;
					         fileOutput.close();  
					         Thread.sleep(50); 
				        }
				       
				         } catch (InterruptedException e) {
				          e.printStackTrace();
				         }catch (MalformedURLException e) {   
				          e.printStackTrace();   
				         } catch (IOException e) {   
				          e.printStackTrace();   
				         }

				       }

			return mValue;
		}
			 public void updateProgress(int downloadedSize, int totalSize) {
				  // TODO Auto-generated method stub
				 mProgress.setProgress(100 * downloadedSize/totalSize); 
				 }

	    protected void onProgressUpdate(Integer... progress) {         
	    	mProgress.setProgress(progress[0]);     
	    //	mText.setText(Integer.toString(progress[0]));     
	    }
	    
	    protected void onPostExecute(Integer result) { 
	    	mProgress.dismiss();
	    }
	    
	    protected void onCancelled() {
			mProgress.dismiss();
	    }
	}
   @Override
	 public boolean onKeyDown(int keyCode, KeyEvent event) {
	  if(event.getAction() == KeyEvent.ACTION_DOWN){
	   if(keyCode == KeyEvent.KEYCODE_BACK && !webview.canGoBack()){
		   finish();
		   return true;
	   }
	   if(keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack())
	   {
		   webview.goBack();
		   return true;
	   }
	  }
	  return false;
	 }
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (adView != null) {
			adView.destroy();
			adView = null;
		}
	  if (mPlayer != null) {
	       	mPlayer.release();
	       	mPlayer = null;
	       }
	mTelMan.listen(mCallListener, PhoneStateListener.LISTEN_NONE);
		
	}

	public void onReceive(int err) {
		// event for receive ad 
		
	}
   
}
